import { setToken, getToken, removeToken } from '@/utils/auth'
import { loginAPI, getUserProfileAPI, getUserPhotoAPI } from '@/api'
import { Message } from 'element-ui'
import router from '@/router'
const getDefaultState = () => {
  return {
    token: getToken() || '',
    userinfo: {}
  }
}
const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  REMOVE_TOKEN: (state) => {
    state.token = ''
    removeToken()
  },
  SET_USER: (state, value) => {
    state.userinfo = value
    // state.userinfo.username = value
    console.log(state.userinfo)
  },
  REMOVE_USER: (state) => {
    state.userinfo = {}
  }
}

const actions = {
  async loginActions({ commit }, { loginForm, redirect }) {
    const [err, res] = await loginAPI(loginForm)
    if (!err) {
      Message({
        type: 'success',
        message: res.data.message
      })
      const token = res.data.data
      commit('SET_TOKEN', token)
      router.push(redirect || '/')
    }

    // return [err, res]
  },
  async getUserInfoActions({ commit }) {
    const res = await getUserProfileAPI()
    const res1 = await getUserPhotoAPI(res.data.data.userId)
    const res2 = { ...res.data.data, ...res1.data.data }
    commit('SET_USER', res2)
    // commit('SET_USER', res.data.data.username)
  },
  async logoutActions(store) {
    removeToken()
    store.commit('REMOVE_TOKEN')
    router.replace(`/login?redirect=${router.currentRoute.fullPath}`)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
